<template>
  <div>
    <el-input readonly :value="value" style="width: 460px">
      <el-button slot="append" @click="onClickSelectFile">选择</el-button>
    </el-input>

    <input :ref="name" type="file" class="file" :accept="accept" @change="onEventFileChange"/>

    <span v-show="progress" class="progress">
      <template v-if="progress === 100">上传完成</template>
      <template v-else>
      {{ progress }}%
      </template>
    </span>
  </div>
</template>

<script>
export default {
  name: 'KFileUpload',
  props: {
    value: String,
    name: String,
    accept: String
  },
  data () {
    return {
      progress: 0
    }
  },
  methods: {
    onClickSelectFile () {
      this.$refs[this.name].click()
    },
    onEventFileChange (evt) {
      const fd = new FormData()
      fd.append('file', evt.target.files[0])
      this.$http.post('admin/upload/file', fd, {
        headers: {'Content-Type':'multipart/form-data'},
        onUploadProgress: (progressEvent) => {
          this.progress = (progressEvent.loaded / progressEvent.total * 100 | 0)
        },
        autoResponse: false
      })
        .then(result => {
          if (result.res_code === 0) {
            this.$emit('success', result.url)
            this.$emit('input', result.url)
          } else {
            this.$emit('error', result.res_msg)
          }
        })
        .catch(err => {
          this.$emit('error', err.message)
        })
    }
  }
};
</script>

<style scoped>
  .file {
    opacity: 0;
    position: absolute;
    left: -100px;
  }
  .progress {
    margin-left: 20px;
  }
</style>
